import { applyMiddleware, compose, createStore } from 'redux'
import thunk from 'redux-thunk'
import { apiMiddleware } from 'redux-api-middleware'
import afterReduxApiMiddleware from 'nmb/redux-middleware/afterReduxApiMiddleware'
import authBeforeReduxApiMiddleware from 'nmb/redux-middleware/authBeforeReduxApiMiddleware'
import reducers from './reducers'

export default (history, initialState = {}) => {
  // ======================================================
  // Middleware Configuration
  // ======================================================
  const middleware = [authBeforeReduxApiMiddleware, apiMiddleware, afterReduxApiMiddleware, thunk];

  // ======================================================
  // Store Enhancers
  // ======================================================
  const enhancers = [];
  if (__DEV__) {
    const devToolsExtension = window.devToolsExtension
    if (typeof devToolsExtension === 'function') {
      enhancers.push(devToolsExtension())
    }
  }

  // ======================================================
  // Store Instantiation and HMR Setup
  // ======================================================
  const createStoreWithMiddleware = compose(applyMiddleware(...middleware), ...enhancers);
  const store = createStoreWithMiddleware(createStore)(reducers, initialState);
  //store.asyncReducers = {};

  // To unsubscribe, invoke `store.unsubscribeHistory()` anytime
  //store.unsubscribeHistory = browserHistory.listen(updateLocation(store));

  if (module.hot) {
    module.hot.accept('./reducers', () => {
      const reducers = require('./reducers').default;
      store.replaceReducer(reducers(store.asyncReducers))
    })
  }

  return store
}